package com.serverdemo.core.processor;

import com.serverdemo.core.entity.SocketEntity;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by wangqiang on 2020/4/10.
 */
public abstract class AbstractProcessor implements Runnable
{
    /**
     * 线程间消息队列
     */
    private ConcurrentLinkedQueue<AbstractProcessorMessage> processorMessages = new ConcurrentLinkedQueue<AbstractProcessorMessage>();

    /**
     * 上次tick时间
     */
    private long lastTickTimestamp;

    public void init()
    {

    }

    public void tick(int interval)
    {

    }

    public void run()
    {
        handleMessage();

        int interval = (int) (System.currentTimeMillis() - lastTickTimestamp);
        tick(interval);

        lastTickTimestamp = System.currentTimeMillis();
    }

    public void handleMessage()
    {
        for (int i = 0; i < 10000; i++)
        {
            AbstractProcessorMessage message = processorMessages.poll();
            if (message == null)
            {
                return;
            }

            dispatchMessage(message);
        }
    }

    /**
     * 派发处理线程间消息
     * @param message
     */
    public abstract void dispatchMessage(AbstractProcessorMessage message);

    /**
     * 进入一个网络对象
     */
    public void addSocketEntity(SocketEntity socketEntity)
    {
    }

    public void receiveMessage(AbstractProcessorMessage message)
    {
        processorMessages.add(message);
    }
}
